<?php

namespace CNEPAdmin\Controller;

use CNEPAdmin\Controller\CommonController;

class GoodsController extends CommonController {

    protected $_modelName = "Goods";

    protected function setCode() {
        $this->_code = "Shop"; // 属于系统管理模块
    }

    /**
     * 得到条件查询数组
     * 
     * @return Array
     */
    protected function _getQueryArr(&$where, &$order) {
        $where = array();
        if (strlen(trim(I("sGoodsName"))) > 0) {
            $where ['goodsName'] = array(
                "like",
                "%" . trim(I("sGoodsName") . "%")
            );
        }
        if (strlen(trim(I("sGoodsSn"))) > 0) {
            $where ['goodsSn'] = array(
                "eq",
                trim(I("sGoodsSn"))
            );
        }
        if (strlen(trim(I("sIsSale"))) > 0 && intval(I("sIsSale")) >= 0) {
            $where ['isSale'] = array(
                "eq",
                intval(I("sIsSale"))
            );
        }
        if (strlen(trim(I("sShopID"))) > 0 && intval(I("sShopID")) > 0) {
            $where ['shopID'] = array(
                "eq",
                intval(I("sShopID"))
            );
        }
        if (strlen(trim(I("sCatID"))) > 0 && intval(I("sCatID")) > 0) {
            $where ['catID'] = array(
                "eq",
                intval(I("sCatID"))
            );
        }
// 		if (strlen ( trim ( I ( "sCommentType" ) ) ) > 0 && intval ( I ( "sCommentType" ) ) >= 0) {
// 			$where ['commentType'] = array (
// 				"eq",
// 				intval ( I ( "sCommentType" ) )
// 			);
// 		}

        $where ['commentType'] = 0;

        $where ['isOn'] = 1;

        $orderBy = 'ind';
        $desc = 'asc';
        if (intval(I("sDesc")) === 1) {
            $desc = 'desc';
        }
        if (strlen(trim(I("sOrderBy", ''))) > 0) {
            $orderBy = I("sOrderBy");
        }

        $order = array(
            $orderBy => $desc
        );
    }

    /**
     * 商店列表
     */
    public function index() {
        $this->checkPriv('goodsMsg', 1, false);

        // 取得商品类型列表
        $catList = D("GoodsCat")->where("isOn = 1 and commentType = 0")->select();
        $this->assign('catList', $catList);
		$this->assign('imgDomain',C('IMG_DOMAIN'));
        $this->_getOnePageData("getGoodsList", "getGoodsListLength");
    }

    /**
     * 保存附属商品
     */
    public function saveGoods() {

        $_POST ['catID'] = I("post.catID", 1);
        $_POST ['commentType'] = 1; // 附属商品
		$_POST['goodsSn'] = strlen(trim(I("goodsSn", ''))) > 0 ? trim(I("goodsSn")) : date('ymd') . substr(time(), -5) . substr(microtime(), 2, 5) . rand(100, 999);
        
        if (I("post.goodsID") > 0) {
            $this->updateGoods($_POST);
        } else {
            $this->addGoods($_POST);
        }
    }

    /**
     * 保存增值商品
     */
    public function saveGoodsForMarket() {
        $this->checkPriv('goodsMsg', 2);

        if (!$this->_checkGoodsVal()) {
            $this->_myAjaxReturn(false);
        }

        $_POST['goodsSn'] = strlen(trim(I("goodsSn", ''))) > 0 ? trim(I("goodsSn")) : date('ymd') . substr(time(), -5) . substr(microtime(), 2, 5) . rand(100, 999);
        $_POST['isSale'] = intval(I("isSale"));
        $_POST ['commentType'] = 0; // 增值商品
        !empty($_POST['headImg'])?$_POST['headImg']=$this->get_url_path(I('post.headImg')):"";
        !empty($_POST['thumb'])?$_POST['thumb']=$this->get_url_path(I('post.thumb')):"";
        !empty($_POST['limitStartTime'])?$_POST['limitStartTime']=strtotime($_POST['limitStartTime']):"";
        !empty($_POST['limitEndTime'])?$_POST['limitEndTime']=strtotime($_POST['limitEndTime']):"";
        
        $this->_setModel();

        // 保存商品基本信息
        if (I("post.goodsID") > 0) {

            if ($this->_model->updateGoods($_POST)) { // 更新之后会删除该商品的所有 sku 组合
                $rt = true;
                $goodsID = I("post.goodsID");
            }
        } else {
            $rt = $this->_model->addGoods($_POST);

            if ($rt)
                $goodsID = $rt;
        }

        if (!$rt) {
            logErr($this->_model->getLastSql() . "\n" . $this->_model->getError() . "\n" . $this->_error . "\n");
            $this->_model->rollback();
        }

        $type = I("post.goodsID") > 0 ? 'update' : 'add'; // 保存类型

        $this->ajaxReturn(array(
            'result' => $rt,
            'desc' => $this->_error,
            'type' => $type,
            'goodsID' => $goodsID,
        ));
    }

    /**
     * 添加
     */
    protected function addGoods() {
    	!empty($_POST['headImg'])?$_POST['headImg']=$this->get_url_path(I('post.headImg')):"";
    	!empty($_POST['thumb'])?$_POST['thumb']=$this->get_url_path(I('post.thumb')):"";
        $this->_ajaxOperate('addGoods', 'goodsMsg', 2);
    }

    private function _checkGoodsVal() {
        $goodsName = trim(I("goodsName", ''));
        $catID = trim(I("catID", ''));
        $shopID = trim(I("shopID", 0));
        $marketPrice = trim(I("marketPrice", ''));
        $goodsPrice = trim(I("goodsPrice", ''));
        $headImg = trim(I("headImg", ''));
        $_POST['ind'] = intval(I("ind", 9999));

        if (empty($goodsName) || empty($catID) || empty($goodsPrice) || $shopID <= 0 || empty($marketPrice) || empty($headImg)) {
            $this->_error = "部分必要数据未填写，请检查后提交";
            return false;
        }
        
        return true;
    }

    /**
     * 删除
     */
    public function deleteGoods() {
        $this->_ajaxOperate('deleteGoods', 'goodsMsg', 2, I("goodsID"));
    }

    /**
     * 查看
     */
    public function goodsMsg() {
        $this->checkPriv('goodsMsg', 1, false);

        $id = intval(I("goodsID", 0));

        if ($id > 0) { // 编辑
            $this->_setModel();
            $arr = $this->_model->getGoods($id);
            $this->assign("arr", $arr);
        }

        // 取得商品类型列表
        $catList = D("GoodsCat")->where("isOn = 1 and commentType = 0")->select();
        $this->assign('catList', $catList);

        $static = C("TMPL_PARSE_STRING");
        $showPic = $arr && strlen($arr['headImg']) > 0 ? $arr['headImg'] : $static['__STATICS__'] . "/images/upload_comn.png";
        $this->assign("showPic", $showPic);
        $this->assign('imgDomain',C('IMG_DOMAIN'));
        $this->display();
    }

    /**
     * 更新基本信息(需要更新什么就提交什么)
     */
    public function updateGoods() {
    	!empty($_POST['headImg'])?$_POST['headImg']=$this->get_url_path(I('post.headImg')):"";
    	!empty($_POST['thumb'])?$_POST['thumb']=$this->get_url_path(I('post.thumb')):"";
        $this->_ajaxOperate('updateGoods', 'goodsMsg', 2);
    }

    public function updateGoodsStatus() {
        $this->checkPriv('goodsMsg', 2);

        $rt = false;

        $id = I("goodsID", 0);
        $status = intval(I("isSale"));

        if ($id > 0) {
            $data = array(
                'goodsID' => $id,
                'isSale' => $status
            );
            $rt = D("Goods")->updateGoods($data);
        }

        $this->_myAjaxReturn($rt);
    }

}
